package org.wzy.xmlg_backend.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.wzy.xmlg_backend.entity.SysUser;
import org.wzy.xmlg_backend.mapper.SysUserMapper;
import org.wzy.xmlg_backend.service.UserService;
import org.wzy.xmlg_backend.utils.JwtUtil;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public SysUser findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public String register(SysUser user) {
        // 检查用户名是否已存在
        if (findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置创建和更新时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 确保角色不为空
        if (user.getRoles() == null || user.getRoles().isEmpty()) {
            user.setRoles("user");
        }

        userMapper.insert(user);

        // 返回生成的token
        return jwtUtil.generateToken(user.getUsername());
    }

    @Override
    public String login(String username, String password) {
        SysUser dbUser = findByUsername(username);
        if (dbUser == null || !passwordEncoder.matches(password, dbUser.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        return jwtUtil.generateToken(dbUser.getUsername());
    }

    @Override
    public SysUser getUserInfo(String username) {
        SysUser user = userMapper.selectByUsername(username);
        if (user != null) {
            // 清理敏感信息
            user.setPassword(null);

            // 确保有角色信息
            if (user.getRoles() == null || user.getRoles().isEmpty()) {
                user.setRoles("user");
            }
        }
        return user;
    }
}
